package com.xky.example_student.controller.teacher;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xky.example_student.annotation.RequirePermission;
import com.xky.example_student.entity.Result;
import com.xky.example_student.entity.Teacher;
import com.xky.example_student.service.TeacherService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Getter
@Slf4j
@RestController
@RequestMapping("/api/teacher")
@Tag(name="教师信息管理")
public class TeacherController {

    private final TeacherService teacherService;

    public TeacherController(TeacherService teacherService) {
        this.teacherService = teacherService;

    }

    /**
     * 保存教师信息
     *
     * @param teacher
     * @return
     */
    @PostMapping("/save")
    @Operation(summary = "保存教师信息")
    @RequirePermission(value = "teacherEdit", message = "您暂时没有添加教师信息的权限")
    public Result<String> saveTeacher(@RequestBody Teacher teacher){
      log.info("保存教师信息");
      teacherService.saveTime1(teacher);
        boolean b = teacherService.saveWithTeaIdCheck(teacher);
        if (b){
            return Result.success("保存成功");
        }else {
            return Result.error("教工号已存在，请检查");
        }
    }

    /**
     * 删除id为xx的教师信息
     * @param id
     * @return
     */
    @DeleteMapping("/removeById")
    @Operation(summary = "删除id为xx的教师信息")
    public Result<Boolean> removeById(@RequestParam("id") Integer id){
        log.info("删除id为{}的教师信息",id);
        teacherService.removeById(id);
        return Result.success();
    }

    /**
     * 批量删除教师信息
     * @param ids
     * @return
     */
    @DeleteMapping("/removeByIds")
    @Operation(summary = "批量删除教师信息")
    public Result<Boolean> removeByIds(@RequestParam("ids") List<Integer> ids){
        log.info("批量删除id为{}的教师信息",ids);
        teacherService.removeByIds(ids);
        return Result.success();
    }

    /**
     * 删除全部的教师信息
     * @return
     */
    @DeleteMapping("/removeAll")
    @Operation(summary = "删除全部的教师信息")
    public Result<String> removeAll(){
        log.info("删除全部的教师信息");
        boolean b = teacherService.removeAll();
        return b ? Result.success("删除成功！") : Result.error("删除失败");
    }

    /**
     * 更新教师信息
     * @param teacher
     * @return
     */
    @PostMapping("/updateById")
    @Operation(summary = "更新教师信息")
    @RequirePermission(value = {"teacherEdit", "canEditProfile"}, message = "您暂时没有修改教师信息的权限")
    public Result<String> updateById(@RequestBody Teacher teacher, HttpServletRequest request){
        log.info("更新id为{}的教师信息", teacher);
        
        // 获取当前登录用户信息
        String userIdStr = request.getHeader("userId");
        String userRole = request.getHeader("role");
        
        if (userIdStr == null || userRole == null) {
            return Result.error("未登录或登录信息无效");
        }
        
        // 如果不是管理员，检查是否在修改自己的信息
        if (!"admin".equals(userRole)) {
            String teacherId = request.getHeader("stuteaid"); // 获取当前登录教师的工号
            if (!teacher.getTeaId().equals(teacherId)) {
                return Result.error("您只能修改自己的信息");
            }
        }
        
        try {
            boolean updated = teacherService.updateById(teacher);
            if (updated) {
                log.info("教师信息更新成功: {}", teacher.getTeaId());
                return Result.success("更新成功");
            } else {
                log.warn("教师信息更新失败: {}", teacher.getTeaId());
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新教师信息时发生错误", e);
            return Result.error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 查询id为xx的教师信息
     * @param id
     * @return
     */
    @GetMapping("/listById")
    @Operation(summary = "查询id为xx的教师信息")
    public Result<Teacher> listById(@RequestParam("id") Integer id){
        log.info("查询id为{}的教师信息",id);
        Teacher byId = teacherService.getById(id);
        if (byId == null){
            return Result.error("查询失败");
        }else {
            return Result.success(byId);
        }
    }

    /**
     * 查询全部的教师信息
     * @return
     */
    @GetMapping("/listAll")
    @Operation(summary = "查询全部的教师信息")
    public Result<List<Teacher>> listAll(){
        log.info("查询全部的教师信息");
        List<Teacher> list = teacherService.list();
        return Result.success(list);
    }

    /**
     * 分页查询
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询")
    public Result<Page<Teacher>> page(@RequestParam("current") Integer current, @RequestParam("size") Integer size){
        log.info("分页查询");
        Page<Teacher> teacherPage = new Page<>(current,size);
        Page<Teacher> page = teacherService.page(teacherPage);
            return Result.success(page);

    }
    
    /**
     * 修复教师tea1的班级数据
     * 仅用于修复数据库中的教师班级不一致问题
     */
    @PostMapping("/fixTeacherClass")
    @Operation(summary = "修复教师班级数据")
    public Result<String> fixTeacherClass() {
        log.info("开始修复教师班级数据");
        
        try {
            // 获取教师tea1的信息
            Teacher teacher = teacherService.getById(12); // 根据数据库中id为12
            if (teacher == null) {
                return Result.error("未找到教师tea1的信息");
            }
            
            log.info("当前教师信息: 工号={}, 姓名={}, 班级={}", 
                teacher.getTeaId(), teacher.getTeaName(), teacher.getTeaCalss());
            
            // 将班级从"3班"修改为"四班"
            teacher.setTeaCalss("四班");
            
            boolean updated = teacherService.updateById(teacher);
            if (updated) {
                log.info("教师班级修复成功: {} -> 四班", teacher.getTeaName());
                return Result.success("教师tea1的班级已从3班修改为四班");
            } else {
                return Result.error("更新失败");
            }
            
        } catch (Exception e) {
            log.error("修复教师班级数据失败", e);
            return Result.error("修复失败：" + e.getMessage());
        }
    }


}

